<template>
  <div class="app-container">
    <el-card shadow="hover" class="main-card mb-4">
      <div class="card-header flex justify-between items-center mb-3">
        <h3 class="text-lg font-semibold">学生注册系统</h3>
        <span class="text-gray-500 text-sm">请确认您的信息并完成注册</span>
      </div>

      <!-- 不在注册时间段时，显示警告提示 -->
      <el-alert
          title="不在注册时间段"
          type="warning"
          :description="`当前不在研究生注册时间段，注册时间为：${timeDesc}`"
          show-icon
          v-if="!inRegistryTime && !isRegistered"
          class="not-in-time-alert"
      />

      <!-- 仅在“在注册时间段”或“已注册”时，显示信息卡片 -->
      <div class="info-container" v-if="inRegistryTime || isRegistered">
        <!-- 学生信息卡片 -->
        <el-card class="info-card mr-4">
          <div slot="header" class="info-card-header flex items-center">
            <el-icon class="mr-2"><User /></el-icon>
            <span>个人信息</span>
          </div>

          <div class="info-content" v-if="studentRegVo">
            <el-descriptions column="1" border>
              <el-descriptions-item label="学号">{{ studentRegVo.studentId }}</el-descriptions-item>
              <el-descriptions-item label="姓名">{{ studentRegVo.studentName }}</el-descriptions-item>
              <el-descriptions-item label="学院">{{ studentRegVo.studentYx }}</el-descriptions-item>
              <el-descriptions-item label="专业">{{ studentRegVo.studentZy }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">
                <el-tag
                    :type="statusTypeMap[studentRegVo.studentZczt]"
                    class="status-tag"
                >{{ studentRegVo.studentZczt || '未注册' }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <el-empty description="加载个人信息失败，请刷新页面重试" v-else></el-empty>
        </el-card>

        <!-- 注册环境信息卡片 -->
        <el-card class="info-card">
          <div slot="header" class="info-card-header flex items-center">
            <el-icon class="mr-2"><Monitor /></el-icon>
            <span>注册环境</span>
          </div>

          <div class="info-content" v-if="regInfo">
            <el-descriptions column="1" border>
              <el-descriptions-item label="IP地址">{{ regInfo.ip }}</el-descriptions-item>
              <el-descriptions-item label="浏览器">{{ regInfo.browser }}</el-descriptions-item>
              <el-descriptions-item label="操作系统">{{ regInfo.os }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <el-empty description="加载环境信息失败，请刷新页面重试" v-else></el-empty>
        </el-card>
      </div>

      <!-- 注册按钮区域 -->
      <div class="registration-action mt-6" v-if="inRegistryTime && !isRegistered">
        <el-button
            type="primary"
            size="large"
            :loading="isLoading"
            @click="handleRegister"
            :disabled="isRegistered || isLoading"
            class="register-button"
        >
          <el-icon v-if="isLoading" class="mr-2"><Loading /></el-icon>
          {{ isLoading ? '注册中...' : '点击完成注册' }}
        </el-button>
      </div>

      <div class="registered-success" v-if="isRegistered">
        <span class="text-success">✓ 您已成功完成注册</span>
      </div>
    </el-card>

    <!-- 注册结果提示 -->
    <el-dialog
        v-model="resultVisible"
        :title="resultTitle"
        :closable="false"
        width="400px"
    >
      <div class="result-content text-center">
        <span v-if="resultType === 'success'" class="success-icon">✓</span>
        <span v-else class="error-icon">×</span>
        <p class="result-message mt-4">{{ resultMessage }}</p>
      </div>
      <template #footer>
        <el-button
            type="primary"
            @click="handleResultConfirm"
            class="result-confirm-btn"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StudentRegistration">
import { ref, reactive, toRefs, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Monitor, Loading } from '@element-plus/icons-vue'

// 导入API接口
import { searchStudentInfo } from '@/api/student/registration'
import { checkRegistrationIP } from '@/api/student/registration'
import { getBrowserInfo } from '@/api/student/registration'
import { checkRegistryTime } from '@/api/student/registration'

// 状态映射表 - 与后端返回的状态文本对应
const statusTypeMap = {
  '未注册': 'primary',
  '待审核': 'warning',
  '已通过': 'success',
  '已驳回': 'info',
  '注册失败': 'danger'
}

// 响应式状态
const state = reactive({
  studentRegVo: null,  // 学生注册信息VO对象
  regInfo: null,       // 注册环境信息对象
  isLoading: false,    // 加载状态
  resultVisible: false,// 结果对话框显示状态
  resultTitle: '注册结果',
  resultMessage: '',   // 结果消息
  resultType: '',      // 结果类型：success/error
  inRegistryTime: false, // 是否在注册时间段内
  timeDesc: ''         // 注册时间段描述
})

const { studentRegVo, regInfo, isLoading, resultVisible, resultTitle, resultMessage, resultType, inRegistryTime, timeDesc } = toRefs(state)

// 计算属性：判断是否已注册
const isRegistered = computed(() => {
  return studentRegVo.value?.studentZczt === '已通过' ||
      studentRegVo.value?.studentZczt === '待审核'
})

/**
 * 获取学生个人信息
 */
function fetchStudentInfo() {
  isLoading.value = true
  searchStudentInfo().then(response => {
    if (response.code === 200) {
      studentRegVo.value = response.data
    } else {
      ElMessage.error(`获取信息失败: ${response.msg || '未知错误'}`)
    }
  }).catch(error => {
    ElMessage.error(`获取信息异常: ${error.message || '网络错误'}`)
    console.error(error)
  }).finally(() => {
    isLoading.value = false
  })
}

/**
 * 获取注册环境信息
 */
function fetchRegistrationEnv() {
  getBrowserInfo().then(response => {
    if (response.code === 200) {
      regInfo.value = response.data
    } else {
      ElMessage.error(`获取环境信息失败: ${response.msg || '未知错误'}`)
    }
  }).catch(error => {
    ElMessage.error(`获取环境信息异常: ${error.message || '网络错误'}`)
    console.error(error)
  })
}

/**
 * 检查是否在注册时间段内
 */
function checkTimeRange() {
  checkRegistryTime().then(response => {
    if (response.code === 200) {
      inRegistryTime.value = response.inTime
      timeDesc.value = response.timeDesc || '未设置'
    } else {
      ElMessage.error(`获取注册时间信息失败: ${response.msg || '未知错误'}`)
      inRegistryTime.value = false
    }
  }).catch(error => {
    ElMessage.error(`检查注册时间异常: ${error.message || '网络错误'}`)
    console.error(error)
    inRegistryTime.value = false
  })
}

/**
 * 处理注册提交
 */
function handleRegister() {
  if (isLoading.value || isRegistered.value || !inRegistryTime.value) return

  isLoading.value = true

  checkRegistrationIP().then(response => {
    if (response.code === 200) {
      resultType.value = 'success'
      resultMessage.value = '注册成功，状态已更新为"已通过"'
      // 重新获取学生信息更新状态
      fetchStudentInfo()
    } else {
      resultType.value = 'error'
      resultMessage.value = response.msg || '注册失败，请稍后重试'
    }
  }).catch(error => {
    resultType.value = 'error'
    resultMessage.value = `注册异常: ${error.message || '网络错误'}`
    console.error(error)
  }).finally(() => {
    isLoading.value = false
    resultVisible.value = true
  })
}

/**
 * 处理结果确认
 */
function handleResultConfirm() {
  resultVisible.value = false
  // 如果注册成功，刷新信息
  if (resultType.value === 'success') {
    fetchStudentInfo()
  }
}

// 页面加载时初始化数据
onMounted(() => {
  // 先检查是否在注册时间内
  checkTimeRange()
  // 再加载学生信息和环境信息
  fetchStudentInfo()
  fetchRegistrationEnv()
})
</script>

<style scoped>
/* 基础样式保持与列表页一致 */
.app-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.main-card {
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.text-lg {
  font-size: 16px;
}

.font-semibold {
  font-weight: 500;
}

.text-gray-500 {
  color: #606266;
}

/* 不在注册时间段提示样式 */
.not-in-time-alert {
  margin: 20px;
}

/* 信息卡片样式 */
.info-container {
  display: flex;
  padding: 20px;
}

.info-card {
  flex: 1;
  transition: all 0.3s ease;
}

.mr-4 {
  margin-right: 16px;
}

.info-card-header {
  color: #409eff;
  font-weight: 500;
}

.info-content {
  margin-top: 15px;
}

/* 注册按钮样式 */
.registration-action {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.register-button {
  width: 200px;
  height: 50px;
  font-size: 16px;
  transition: all 0.2s;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.registered-success {
  display: flex;
  align-items: center;
  font-size: 16px;
  padding: 15px 0;
  justify-content: center;
}

.text-success {
  color: #67c23a;
}

/* 结果对话框样式 */
.result-icon {
  font-size: 48px;
  display: inline-block;
  width: 48px;
  height: 48px;
  line-height: 48px;
  border-radius: 50%;
}

.success-icon {
  color: white;
  background-color: #67c23a;
}

.error-icon {
  color: white;
  background-color: #f56c6c;
}

.result-message {
  font-size: 16px;
  color: #333;
}

.result-confirm-btn {
  width: 120px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .info-container {
    flex-direction: column;
  }

  .info-card {
    margin-bottom: 16px;
  }

  .mr-4 {
    margin-right: 0;
  }
}
</style>
